package com.xcloud.component.db;

import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.core.toolkit.support.SerializedLambda;
import org.apache.ibatis.reflection.property.PropertyNamer;
public class ExtSqlProvider {

    private String oneField(SFunction<?, ?> column,String format) {
        SerializedLambda lambda = LambdaUtils.resolve(column);
        Class<?> aClass = lambda.getInstantiatedType();
        String tableName = TableInfoHelper.getTableInfo(aClass).getTableName();
        String fieldName = PropertyNamer.methodToProperty(lambda.getImplMethodName());
        return String.format(format,tableName,fieldName);
    }

    public String listByOneField(SFunction<?, ?> column) {
        String format = "SELECT * FROM %s WHERE %s = #{val}";
        return oneField(column,format);
    }

    public String getByOneField(SFunction<?, ?> column) {
        String format = "SELECT * FROM %s WHERE %s = #{val} LIMIT 1";
        return oneField(column,format);
    }

    public String deleteByOneField(SFunction<?, ?> column) {
        String format = "DELETE FROM %s WHERE %s = #{val}";
        return oneField(column,format);
    }

    private String twoField(SFunction<?, ?> column1,SFunction<?, ?> column2,String format) {
        SerializedLambda lambda1 = LambdaUtils.resolve(column1);
        Class<?> aClass = lambda1.getInstantiatedType();
        String tableName = TableInfoHelper.getTableInfo(aClass).getTableName();
        String fieldName1 = PropertyNamer.methodToProperty(lambda1.getImplMethodName());
        SerializedLambda lambda2 = LambdaUtils.resolve(column2);
        String fieldName2 = PropertyNamer.methodToProperty(lambda2.getImplMethodName());
        return String.format(format,tableName,fieldName1,fieldName2);
    }

    public String listByTwoField(SFunction<?, ?> column1,SFunction<?, ?> column2) {
        String format = "SELECT * FROM %s WHERE %s = #{val1} AND %s = #{val2}";
        return twoField(column1,column2,format);
    }

    public String getByTwoField(SFunction<?, ?> column1,SFunction<?, ?> column2) {
        String format = "SELECT * FROM %s WHERE %s = #{val1} AND %s = #{val2} LIMIT 1";
        return twoField(column1,column2,format);
    }

    public String deleteByTwoField(SFunction<?, ?> column1,SFunction<?, ?> column2) {
        String format = "DELETE FROM %s WHERE %s = #{val1} AND %s = #{val2}";
        return twoField(column1,column2,format);
    }
}
